package com.mjr.webmanage.filter;

import com.mjr.webmanage.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        String url = request.getRequestURL().toString();
        log.info("拦截的请求：{}", url);
        if (url.contains("/login")) {
            log.info("----------->登录请求，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("Token");

        // 令牌不存在 响应401
        if (!StringUtils.hasLength(token)) {
            log.info("----------->令牌不存在 ，响应401");
            response.setStatus(401);
            return;
        }
        // 令牌存在，解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("----------->令牌解析成功，放行");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("----------->令牌解析失败，响应401");
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
